package com.taomeishu.mailcrazy.checkers.hotmail;

import java.util.List;

import com.taomeishu.mailcrazy.CheckResult;
import com.taomeishu.mailcrazy.Mail;
import com.taomeishu.mailcrazy.http.ClientResponse;
import com.taomeishu.mailcrazy.parser.ResultParseException;
import com.taomeishu.mailcrazy.parser.ResultParser;

public class HotmailResultParser implements ResultParser {

	@Override
	public CheckResult parse(ClientResponse clientResponse, String username, String domainName) throws ResultParseException {
		List<String> cookies = clientResponse.getHeaders().get("Set-Cookie");
		CheckResult result = new CheckResult(true);
		Mail mail = new Mail(username, domainName);
		result.setMail(mail);
		if (cookies == null || cookies.size() == 0) {
			throw new ResultParseException("hotmail cookie not set!");
		}
		String cookie = cookies.get(0);
		if (exist(cookie)) {
			result.addExistMail(mail);
		} else {
			result.addNotExistMail(mail);
		}
		return result;
	}
	
	private boolean exist(String cookie) throws ResultParseException {
		String[] responseCookies = cookie.split(";");
		for (String responseCookie : responseCookies) {
			String[] kvs = responseCookie.split("=");
			String k = kvs[0].trim();
			String v = kvs[1].trim();
			if (k.equals("MSPMemberExists")) {
				return "MemberExists".equals(v);
			}
		}
		throw new ResultParseException("hotmail cookie MSPMemberExists not set!");
	}

}
